package com.hit.client.comm;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class ChannelCache {


    public static volatile Map<ChannelId, ChannelHandlerContext> channelHandlerContextMap = new ConcurrentHashMap<>();

    public static void add(ChannelHandlerContext ctx) {
        log.info("添加通道数据 {}---{}", ctx.channel().remoteAddress().toString(), ctx.channel().id());
        channelHandlerContextMap.put(ctx.channel().id(), ctx);
    }

    public static void remove(ChannelHandlerContext ctx) {
        channelHandlerContextMap.remove(ctx.channel().id());
    }

    public static ChannelHandlerContext findByChannelId(ChannelId channelId) {
        return channelHandlerContextMap.get(channelId);
    }

    public static void send2All(Object object) {
        for (ChannelId channelId : channelHandlerContextMap.keySet()) {
            ChannelHandlerContext ctx = channelHandlerContextMap.get(channelId);
            if (ctx != null) {
                ctx.channel().writeAndFlush(object);
            }
        }
    }

}
